package org.restorator.controller.security;

import org.restorator.entity.User;
import org.restorator.service.UserService;
import org.restorator.service.impl.UserServiceImpl;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

import static org.restorator.utill.ControllerUtil.*;

/**
 *
 *
 *
 * @author Snisar Bogdan.
 */
@WebServlet(name = "login", urlPatterns = "/login")
public class LoginController extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());

    private static char[] CHAR_ARRAY = {'A','B','C','D','E','F'};

    /**
     * Parameter for request that must contains password value for login operation
     */
    private static final String PARAM_PASS = "password";

    /**
     * Parameter for request that must contains login value for login operation
     */
    private static final String PARAM_LOGIN = "login";

    @Override
    public void init() throws ServletException {
        userService= new UserServiceImpl();
        random = new Random();
    }

    /**
     * Service for operation with user entity
     */
    private UserService userService;


    private Random random;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.trace("new login request");

        try {
            String password = req.getParameter(PARAM_PASS);
            String login = req.getParameter(PARAM_LOGIN);
            if(password == null || login == null) {
                logger.trace("get password {} and login as parameters", password, login);
                printError(resp, "empty password or login");
                return;
            }
//            OK, not empty params
            User user = userService.getUserByLoginAndPass(password, login);
            logger.trace("try to find user: {} by login and password", user);

            if(user != null) {
                String key = generateKey();
                logger.trace("test: generate key {}", key);
                user.setKey(key);

                userService.update(user);
                logger.trace("user update success");

//                All ok, return key
                printOk(resp, key);
            }
        } catch (Exception e) {
            printError(resp.getWriter(), "error in request");
        }

    }

    private String generateKey() {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 30; i++) {
            int value = random.nextInt(16);
            if(value > 10) {
                sb.append(CHAR_ARRAY[16-value]);
            } else {
                sb.append(value);
            }
        }
        return sb.toString();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
